import React, { Fragment } from 'react'
import { View, StyleSheet, Text } from 'react-native'
import { connect } from 'react-redux'
import { ScaleS, ScaleT } from 'src/utils/ScreenUtil'
import { UPDATE_USERINFO_ACTION } from 'src/store/actions/userinfo'
import BaseManager from 'src/pageP/base/base-manager'
import CustomImage from 'src/components/image/CustomImage'
import CustomButton from 'src/components/button/CustomButton'

import showPicker from 'src/utils/PickerUtil'
import { generateFullTimeByYear, generateYearFromNow, getYearFromFullTime } from 'src/utils/TimeUtil'
import { CommonToast } from 'src/utils/ToastUtil'
import { education, getDegreeLabelByLevel, getDegreeLevelByLabel } from 'src/utils/ConfigUtil'
import {
  DO_REQUEST_DEL_EDUCATION, DO_REQUEST_FIND_PROFESSION, DO_REQUEST_FIND_SCHOOL,
  DO_REQUEST_INSERT_EDUCATION, DO_REQUEST_UPDATE_EDUCATION,
  DO_REQUEST_USER_ARCHIVE_EDUCATION,
  UPDATE_USER_ARCHIVE_EDUCATION_ACTION
} from '../../mine/mine-page/store/action'
import { getProfessionQuery, getSchoolQuery } from '../../../utils/FuzzyQueryUtil'
import { showTipModal } from '../../../utils/ModalUtil'
import CustomTextEllipsize from '../../../components/custom-text-ellipsize/index'

const arrowRightImg = require('src/imgC/userinfo/arrow_black_right.png')
// 发送行为
const mapDispatchToProps = dispatch => ({
  updateUserInfo (payload) {
    dispatch(UPDATE_USERINFO_ACTION(payload))
  },
  updateUserArchiveEducation (payload) {
    dispatch(UPDATE_USER_ARCHIVE_EDUCATION_ACTION(payload))
  },
  doRequestUserArchiveEducation (payload) {
    const promise = DO_REQUEST_USER_ARCHIVE_EDUCATION(payload)
    dispatch(promise)
    return promise.payload
  },
  doRequestInsertEducation (payload) {
    const promise = DO_REQUEST_INSERT_EDUCATION(payload)
    return promise.payload
  },
  doRequestUpdateEducation (payload) {
    const promise = DO_REQUEST_UPDATE_EDUCATION(payload)
    return promise.payload
  },
  doRequestDelEducation (payload) {
    const promise = DO_REQUEST_DEL_EDUCATION(payload)
    return promise.payload
  },
  doRequestFindProfession (payload) {
    const promise = DO_REQUEST_FIND_PROFESSION(payload)
    return promise.payload
  },
  doRequestFindSchool (payload) {
    const promise = DO_REQUEST_FIND_SCHOOL(payload)
    return promise.payload
  }
})

@connect(state => state, mapDispatchToProps)
class CEducationInfoManager extends BaseManager {
  constructor (props) {
    super(props)
    const {
      navigation: {
        state: { params }
      }
    } = this.props
    this.state = {
      ...this.state,
      education: (params && params.education) || null
    }
    this.showDeleteCompleteBtn = params && params.showDelete
    this.titleText = '教育信息'
    this.completeText = '删除本条'
    this.config = {
      onCancel: this.onCancel,
      onConfirm: this.onConfirm,
      contentText: '确定删除这条教育信息吗？'
    }
    this.educationStartTime = generateYearFromNow(20, 3)
    this.educationEndTime = generateYearFromNow(20)
    this.degreeLabel = this.generateDegreeLabel()
    this.isEditEducation = params
    this.allSchools = []
    this.allProfessions = []
  }

  generateDegreeLabel = () => {
    return education.map((item) => {
      return item.key
    })
  }

  onSave = () => {
    const { doRequestInsertEducation, doRequestUpdateEducation, userinfo, CMineCenterStore, updateUserArchiveEducation } = this.props
    const { education } = this.state
    if (education) {
      if (!education.schoolName) {
        CommonToast('请填写学校名称')
        return
      }
      if (!education.degreeLevel) {
        CommonToast('请选择学历')
        return
      }
      if (!education.majorName) {
        CommonToast('请填写专业名称')
        return
      }
      if (!education.beginTime) {
        CommonToast('请选择起止时间')
        return
      }
    } else {
      CommonToast('请完善教育信息')
      return
    }
    const paramsEducation = {
      beginTime: education.beginTime,
      degreeLevel: education.degreeLevel,
      endTime: education.endTime,
      majorName: education.majorName,
      schoolName: education.schoolName,
      userId: userinfo.userId
    }
    if (this.isEditEducation) {
      paramsEducation.id = education.id
      doRequestUpdateEducation(paramsEducation).then((education) => {
        CommonToast('更新成功')
        const educations = CMineCenterStore.educations.map((item) => {
          return item.id === education.id ? education : item
        })
        this._updateEducation(educations)
      })
    } else {
      doRequestInsertEducation(paramsEducation).then((education) => {
        CommonToast('添加成功')
        const educations = CMineCenterStore.educations.concat(education)
        this._updateEducation(educations)
      })
    }
  }

  _updateEducation = (educations) => {
    const { updateUserArchiveEducation, CMineCenterStore, navigation } = this.props
    updateUserArchiveEducation({
      educations
    })
    navigation.goBack()
    // if (CMineCenterStore.educations.length > 0) {
    //   navigation.goBack()
    // } else {
    //   navigation.navigate('CMainTab')
    // }
  }

  componentDidMount () {
    const { doRequestFindProfession, doRequestFindSchool } = this.props
    doRequestFindProfession({}).then(data => {
      console.info(data)
      this.allProfessions = data
    })
    doRequestFindSchool({}).then(data => {
      console.info(data)
      this.allSchools = data
    })
  }

  childContentRender () {
    const { education } = this.state
    return (
      <Fragment>
        <CustomButton style={styles.itemView} onPress={this.goSchoolSelect}>
          <View style={styles.itemContentView}>
            <Text style={styles.leftLabel}>学校名称</Text>
            <CustomTextEllipsize style={styles.rightLabel} text={(education && education.schoolName) || '请输入'}/>
            <CustomImage style={styles.rightImg} source={arrowRightImg}/>
          </View>
          <View style={styles.itemLine}/>
        </CustomButton>
        <CustomButton style={styles.itemView} onPress={this.showEduBackgroundPicker}>
          <View style={styles.itemContentView}>
            <Text style={styles.leftLabel}>学历</Text>
            <Text
              style={styles.rightLabel}>{(education && getDegreeLabelByLevel(education.degreeLevel)) || '请选择'}</Text>
            <CustomImage style={styles.rightImg} source={arrowRightImg}/>
          </View>
          <View style={styles.itemLine}/>
        </CustomButton>
        <CustomButton style={styles.itemView} onPress={this.goProfessionName}>
          <View style={styles.itemContentView}>
            <Text style={styles.leftLabel}>专业</Text>
            <Text style={styles.rightLabel}>{(education && education.majorName) || '请输入'}</Text>
            <CustomImage style={styles.rightImg} source={arrowRightImg}/>
          </View>
          <View style={styles.itemLine}/>
        </CustomButton>
        <CustomButton style={styles.itemView} onPress={this.showTimePicker}>
          <View style={styles.itemContentView}>
            <Text style={styles.leftLabel}>起止时间</Text>
            <Text
              style={styles.rightLabel}>{education && education.beginTime && education.endTime ? `${getYearFromFullTime(education.beginTime)}-${getYearFromFullTime(education.endTime)}` : '请选择'}</Text>
            <CustomImage style={styles.rightImg} source={arrowRightImg}/>
          </View>
          <View style={styles.itemLine}/>
        </CustomButton>
      </Fragment>
    )
  }

  onCancel = () => {
    this.toggleTipPrompt(false)
  }

  onConfirm = () => {
    this.toggleTipPrompt(false, this._deleteEducation)
  }

  onComplete () {
    this.toggleTipPrompt(true)
  }

  _deleteEducation = () => {
    const { doRequestDelEducation, userinfo, CMineCenterStore } = this.props
    const { education } = this.state
    const paramsEducation = {
      id: education.id,
      userId: userinfo.userId
    }
    doRequestDelEducation(paramsEducation).then(() => {
      CommonToast('删除成功')
      const educations = CMineCenterStore.educations.filter((item) => {
        return item.id !== education.id
      })
      this._updateEducation(educations)
    })
  }

  toggleTipPrompt = (showTip, callBack) => {
    if (showTip) {
      this.tipPrompModal = showTipModal(this.config)
    } else {
      if (this.tipPrompModal) {
        this.tipPrompModal.close(() => {
          callBack && callBack()
        })
      }
    }
  }

  goSchoolSelect = () => {
    const { education } = this.state
    this.props.navigation.navigate('CommonInputListPage', {
      title: '学校名称',
      value: education ? education.schoolName : '',
      desc: '*支持全国所有院校名称',
      placeholder: '请输入学校名称',
      maxLength: 46,
      saveCallback: this.schoolSave,
      associativeRequest: this._schoolAssociative
    })
  }

  _schoolAssociative = (editValue) => {
    return new Promise((resolve) => {
      resolve(getSchoolQuery(this.allSchools, editValue))
    })
  }

  schoolSave = (value) => {
    console.info(value)
    this.setEducationState({
      schoolName: value
    })
  }

  goProfessionName = () => {
    const { education } = this.state
    this.props.navigation.navigate('CommonInputListPage', {
      title: '专业名称',
      value: education ? education.majorName : '',
      desc: '*输入你所学习的专业名称',
      placeholder: '请输入专业名称',
      maxLength: 16,
      saveCallback: this.professionSave,
      associativeRequest: this._professionAssociative
    })
  }

  _professionAssociative = (editValue) => {
    return new Promise((resolve) => {
      resolve(getProfessionQuery(this.allProfessions, editValue))
    })
  }

  professionSave = (value) => {
    console.info(value)
    this.setEducationState({
      majorName: value
    })
  }

  showEduBackgroundPicker = () => {
    const { education } = this.state
    const selectedValue = education && education.degreeLevel ? [getDegreeLabelByLevel(education.degreeLevel)] : []
    showPicker({
      pickerData: this.degreeLabel,
      selectedValue: selectedValue,
      pickerTitleText: '选择学历',
      onConfirm: this.degreeLevelConfirm
    })
  }

  degreeLevelConfirm = (data) => {
    const degreeLevel = getDegreeLevelByLabel(data[0])
    this.setEducationState({
      degreeLevel: degreeLevel
    })
  }

  showTimePicker = () => {
    const { education } = this.state
    const selectedValue = education && education.beginTime && education.endTime ? [getYearFromFullTime(education.beginTime), getYearFromFullTime(education.endTime)] : []
    showPicker({
      pickerData: [this.educationStartTime, this.educationEndTime],
      selectedValue: selectedValue,
      pickerTitleText: '起止时间',
      onConfirm: this.educationTimeConfirm
    })
  }

  educationTimeConfirm = (data) => {
    console.info(data)
    if (data[0] > data[1]) {
      CommonToast('起始时间不可超过结束时间')
    } else {
      this.setEducationState({
        beginTime: generateFullTimeByYear(data[0]),
        endTime: generateFullTimeByYear(data[1])
      })
    }
  }

  setEducationState = (otherEducation) => {
    const { education } = this.state
    this.setState({
      education: {
        ...education,
        ...otherEducation
      }
    })
  }
}

export default CEducationInfoManager

const styles = StyleSheet.create({
  container: {
    flex: 1
  },
  itemView: {
    height: ScaleS(76),
    paddingHorizontal: ScaleS(20)

  },
  itemContentView: {
    height: ScaleS(75),
    flexDirection: 'row',
    alignItems: 'center'
  },
  leftLabel: {
    color: '#444444',
    fontSize: ScaleT(16),
    fontWeight: '600',
    flex: 1
  },
  rightLabel: {
    color: '#444444',
    fontSize: ScaleT(16),
    fontWeight: '400',
    marginRight: ScaleS(16),
    maxWidth: ScaleS(230)
  },
  rightImg: {
    width: ScaleS(6),
    height: ScaleS(12)
  },
  itemLine: {
    height: ScaleS(1),
    backgroundColor: '#EFEFEF'
  }
})
